#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from web.manager.log_manager import LogManager
from web.service.base_service import BaseService
from web.config.model_commodity_future_hour_data_config import \
    ModelCommodityFutureHourDataConfig
from web.constants.file_and_path import FileAndPath
from web.util.math_util import MathUtil

Logger = LogManager.get_logger(__name__)

"""
ModelCommodityFutureHourDataMACDGoldCross的service类
"""


class ModelCommodityFutureHourDataMACDDeadCrossService(BaseService):

    def add_oracle_column_comment(self):
        """
        为表mdl_c_f_hour_macd_dead_cross添加注释
        """

        Logger.info('为表mdl_c_f_hour_macd_dead_cross添加注释')

        self.model_commodity_future_hour_data_macd_dead_cross_dao.add_oracle_column_comment()

    ########################################### 全量计算数据 ########################################

    def write_hour_all_macd_dead_cross(self):
        """
        1小时级别，MACD死叉算法
        """

        Logger.info("1小时级别，MACD死叉算法")

        self.model_commodity_future_hour_data_macd_dead_cross_dao.write_hour_all_macd_dead_cross()

    ########################################### 增量计算数据 ########################################

    def write_hour_all_macd_dead_cross_by_date(self):
        """
        根据日期，计算1小时级别，MACD死叉算法
        """

        Logger.info("根据日期，计算1小时级别，MACD死叉算法")

        self.model_commodity_future_hour_data_macd_dead_cross_dao.write_hour_all_macd_dead_cross_by_date(
            ModelCommodityFutureHourDataConfig.MACD_Dead_Cross_Begin_Time,
            ModelCommodityFutureHourDataConfig.MACD_Dead_Cross_End_Time)

    #################################### 创建MACD死叉算法收益率折线图 #################################

    def create_and_save_macd_dead_cross_accumulative_profit_loss_line_chart(self):
        """
        创建MACD死叉算法收益率折线图
        """

        Logger.info("创建MACD死叉算法收益率折线图")

        commodity_future_info_list = self.commodity_future_info_dao.filter(tradable=1).find_all()

        if commodity_future_info_list != None and len(commodity_future_info_list) != 0:
            for commodity_future_info in commodity_future_info_list:
                code = commodity_future_info.code
                Logger.info("期货代码：%s", code)

                # 日期
                date_list = list()
                # ma5
                # ma5_list = list()
                # # ma10
                # ma10_list = list()
                # # ma20
                # ma20_list = list()
                # ma60
                ma60_list = list()
                # ma120
                ma120_list = list()
                # ma250
                ma250_list = list()
                # 某只期货的收盘价
                commodity_future_hour_data_close_price_list = list()
                # macd死叉收益率
                mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list = list()

                # 查找某个期货全部交易记录，并按transaction_date升序排列
                commodity_future_hour_data_list = self.commodity_future_hour_data_dao.find_list_by_code_order_by_transaction_date_asc(
                    code)

                # 上一个macd死叉算法收益率
                last_accumulative_profit_loss = 100
                if commodity_future_hour_data_list != None and len(commodity_future_hour_data_list) > 0:
                    for commodity_future_hour_data in commodity_future_hour_data_list:
                        date_list.append(commodity_future_hour_data.transaction_date)

                        # if commodity_future_hour_data.ma5 != None:
                        #     ma5_list.append(commodity_future_hour_data.ma5)
                        # else:
                        #     ma5_list.append(commodity_future_hour_data.close_price)
                        # if commodity_future_hour_data.ma10 != None:
                        #     ma10_list.append(commodity_future_hour_data.ma10)
                        # else:
                        #     ma10_list.append(commodity_future_hour_data.close_price)
                        # if commodity_future_hour_data.ma20 != None:
                        #     ma20_list.append(commodity_future_hour_data.ma20)
                        # else:
                        #     ma20_list.append(commodity_future_hour_data.close_price)
                        if commodity_future_hour_data.ma60 != None:
                            ma60_list.append(commodity_future_hour_data.ma60)
                        else:
                            ma60_list.append(commodity_future_hour_data.close_price)
                        if commodity_future_hour_data.ma120 != None:
                            ma120_list.append(commodity_future_hour_data.ma120)
                        else:
                            ma120_list.append(commodity_future_hour_data.close_price)
                        if commodity_future_hour_data.ma250 != None:
                            ma250_list.append(commodity_future_hour_data.ma250)
                        else:
                            ma250_list.append(commodity_future_hour_data.close_price)

                        commodity_future_hour_data_close_price_list.append(commodity_future_hour_data.close_price)

                        # 根据code和buy_date，查找记录
                        model_commodity_future_hour_data_macd_dead_cross = self.model_commodity_future_hour_data_macd_dead_cross_dao.find_by_code_and_buy_date(
                            code, commodity_future_hour_data.transaction_date)

                        if model_commodity_future_hour_data_macd_dead_cross != None:
                            mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list.append(
                                model_commodity_future_hour_data_macd_dead_cross.accumulative_profit_loss)
                            last_accumulative_profit_loss = model_commodity_future_hour_data_macd_dead_cross.accumulative_profit_loss
                        else:
                            mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list.append(
                                last_accumulative_profit_loss)

                    # 归一化
                    commodity_future_hour_data_close_price_list = MathUtil.normalize(
                        commodity_future_hour_data_close_price_list)
                    # ma5_list = MathUtil.normalize(ma5_list)
                    # ma10_list = MathUtil.normalize(ma10_list)
                    # ma20_list = MathUtil.normalize(ma20_list)
                    ma60_list = MathUtil.normalize(ma60_list)
                    ma120_list = MathUtil.normalize(ma120_list)
                    ma250_list = MathUtil.normalize(ma250_list)
                    mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list = MathUtil.normalize(
                        mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list)

                    # 创建一个新的图表
                    fig, ax = plt.subplots(figsize=(18, 8))

                    # 关闭交互模式
                    plt.ioff()

                    # 创建折线图
                    ax.plot(date_list, commodity_future_hour_data_close_price_list[0], label='期货收盘价',
                            linewidth=0.5)
                    # ax.plot(date_list, ma5_list[0], label='MA5', linewidth=0.5)
                    # ax.plot(date_list, ma10_list[0], label='MA10', linewidth=0.5)
                    # ax.plot(date_list, ma20_list[0], label='MA20', linewidth=0.5)
                    ax.plot(date_list, ma60_list[0], label='MA60', linewidth=0.5)
                    ax.plot(date_list, ma120_list[0], label='MA120', linewidth=0.5)
                    ax.plot(date_list, ma250_list[0], label='MA250', linewidth=0.5)
                    ax.plot(date_list, mdl_c_f_hour_data_macd_d_c_accumulative_profit_loss_list[0],
                            label='MACD死叉算法收益率', linewidth=0.5)

                    # 分辨率
                    plt.rcParams['savefig.dpi'] = 300

                    # 显示图例
                    # plt.legend()

                    # 保存图表
                    plt.savefig(
                        FileAndPath.System_Drive + '/mywork/gitcode-repository/hades/dev-project/adam3/output/picture/macd_dead_cross_accumulative_profit_loss_line_chart/macd_dead_cross_accumulative_profit_loss_line_chart_' + code.replace(
                            '/', '-') + '.png')

                    # 显示图表
                    # plt.show()

                    # 关闭图表
                    plt.close()
